package inspect

import (
	"context"
	daqapp "daqctl/internal/app"
	appstate "daqctl/internal/app/state"
	"daqctl/internal/config"
	"errors"
	"fmt"

	"github.com/go-redis/redis/v8"

	"github.com/spf13/cobra"
)

// AppInspect 获得App详细信息
func PrintAppInspect(cmd *cobra.Command, args []string) {
	appName, err := cmd.Flags().GetString("name")
	cobra.CheckErr(err)
	appType, err := cmd.Flags().GetString("type")
	cobra.CheckErr(err)

	var apps []daqapp.App

	if appName != "" {
		//查看某个app
		apps = []daqapp.App{
			{
				Name:    appName,
				Type:    daqapp.MatchAppType(appName),
				State:   "None",
				Desc:    daqapp.MatchAppTypeDesc(appName),
				Metrics: map[string]string{},
			},
		}
	} else if appType != "" {
		//查看某种app
		switch daqapp.MatchAppType(appType) {
		case daqapp.ROSType:
			apps = daqapp.ROSApps()
		case daqapp.BuilderType:
			apps = daqapp.BuilderApps()
		case daqapp.PSType:
			apps = daqapp.PSApps()
		case daqapp.ESType:
			apps = daqapp.ESApps()
		case daqapp.DFMType:
			apps = daqapp.DFMApps()
		}
	} else {
		//查看所有app
		apps = daqapp.Apps()
	}

	err = appstate.GetAppState(config.DaqCtlConfig.Partition, apps, config.RedisCli)
	cobra.CheckErr(err)

	err = GetAppMetrics(apps, config.RedisCli)
	cobra.CheckErr(err)

	for _, app := range apps {
		fmt.Printf("%+v\n", app)
	}
}

// GetAppMetrics 获取metrics
func GetAppMetrics(apps []daqapp.App, redisCli *redis.Client) error {
	for _, app := range apps {
		var keys []string
		var metricNames []string

		switch app.Type {
		case daqapp.ROSType:
			metricNames = daqapp.GetROSMetricNames()
		case daqapp.BuilderType:
			metricNames = daqapp.GetBuilderMetricNames()
		case daqapp.PSType:
			metricNames = daqapp.GetProcessorMetricNames()
		case daqapp.ESType:
			metricNames = daqapp.GetEventStorageMetricNames()
		case daqapp.DFMType:
			metricNames = daqapp.GetDFMMetricNames()
		default:
			return errors.New("no such app type for metrics")
		}

		for _, metricName := range metricNames {
			key := fmt.Sprintf(daqapp.ROSMetricsPattern, app.Name, metricName)
			keys = append(keys, key)
		}

		res := redisCli.MGet(context.Background(), keys...)

		sc, err := res.Result()
		if err != nil {
			return err
		}

		for i := 0; i < len(sc); i++ {
			m := sc[i]
			if m == nil {
				app.Metrics[metricNames[i]] = ""
			} else {
				app.Metrics[metricNames[i]] = m.(string)
			}
		}
	}

	return nil
}
